package br.com.sguc.manegedBean;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

import br.com.sguc.entidade.Equipe;

@FacesConverter(value = "EquipeConverter")
public class EquipeConversor implements Converter {

	public Object getAsObject(FacesContext context, UIComponent component,String value) {

		return getObjectFromUIPickListComponent(component, value);
	}

	public String getAsString(FacesContext context, UIComponent component,
			Object object) {
		String string;
		if (object == null) {
			string = "";
		} else {
			try {
				string = String.valueOf(((Equipe) object).getIdEquipe());
			} catch (ClassCastException cce) {
				throw new ConverterException();
			}
		}
		return string;
	}

	@SuppressWarnings("unchecked")
	private Equipe getObjectFromUIPickListComponent(UIComponent component,String value) {
		
		final DualListModel<Equipe> dualList;
		
		try {
			dualList = (DualListModel<Equipe>) ((PickList) component).getValue();
			Equipe equipe = getObjectFromList(dualList.getSource(),Integer.valueOf(value));
			if (equipe == null) {
				equipe = getObjectFromList(dualList.getTarget(),Integer.valueOf(value));
			}

			return equipe;
		} catch (ClassCastException cce) {
			throw new ConverterException();
		} catch (NumberFormatException nfe) {
			throw new ConverterException();
		}
	}

	private Equipe getObjectFromList(final List<?> list,
			final Integer identifier) {
		for (final Object object : list) {
			final Equipe equipe = (Equipe) object;
			if (equipe.getIdEquipe().equals(identifier)) {
				return equipe;
			}
		}
		return null;
	}
}